package cn.snsprj.authserver.util;

import cn.snsprj.authserver.common.ConstCode.ConstCodeCookie;
import cn.snsprj.authserver.common.ConstCode.ConstCodeUrl;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * @author SKH
 * @date 2018-08-20 14:50
 **/
public class URLUtil {

    /**
     * 构造重定向url
     *
     * @param url url
     * @param params 只支持普通 key value
     * @return
     */
    public static String redirect(String url, Map<String, Object> params){

        String redirectPrefix = "redirect:";

        return genURL(redirectPrefix, url, params);
    }

    private static String genURL(String prefix, String url, Map<String, Object> params){

        if (params == null || params.isEmpty()){
            return prefix + url;
        }else {
            Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();

            StringBuilder paramStrBuilder = new StringBuilder("?");
            // 检查URL中是否有参数
            if (StringUtils.contains(url, "?")){
                paramStrBuilder = new StringBuilder("&");
            }

            while (entries.hasNext()){

                Map.Entry<String, Object> entry = entries.next();
                String key = entry.getKey();
                Object value = entry.getValue();

                try {

                    // 编码value
                    URLEncoder.encode(String.valueOf(entry.getValue()), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                paramStrBuilder.append(key).append("=").append(value).append("&");
            }

            String paramStr = paramStrBuilder.toString();

            return prefix + url + paramStr;
        }
    }

    /**
     * 带有ST的重定向
     * @param url url
     * @param serviceTicket serviceTicket
     * @return
     */
    public static String redirectWithST(String url, String serviceTicket){

        Map<String, Object> params = new HashMap<>();
        params.put(ConstCodeCookie.COOKIE_SERVICE_TICKET,serviceTicket);

        return redirect(url,params);
    }

    /**
     * 重定向
     *
     * @param url url
     * @return
     */
    public static String redirect(String url){
        return redirect(url,null);
    }

    public static String getURLWithST(String url, String serviceTicket){
        return genURL("", url, null);
    }
}
